#include "delay.h"
#include <REGX52.H>

static volatile uint8_t data timer_tick;//count of 1/16s

void T0_ISR(void) interrupt 1 using 1 {
#pragma ASM
	CLR     EA
	CLR		TR0 ;停止计时器，防止高低位读取时错误
	MOV     A, #LOW(COUNT_RELOAD)
	ADD     A, TL0
	MOV     TL0, A ;TL加上重载值低位
	MOV     A, #HIGH(COUNT_RELOAD)
	ADDC    A, TH0
	MOV     TH0, A ;TH加上重载值高位
	SETB    TR0 ;恢复计时器
	SETB    EA ;恢复中断
	JNC     NC ;如果刚刚的加法溢出了(C=1)，表示我们错过了一次中断（虽然可能性很小）
	INC     timer_tick
NC:	INC     timer_tick	
#pragma ENDASM
}

void delay_Init(void) {
	TMOD &= 0xF0;
	TMOD |= 0x01;//T0 = 16 bit mode
	TR0 = 1;//run
	ET0 = 1;//enable interrupt
	EA = 1;//enable global interrupt
}

//continued: 从上次计时继续
void delay(uint16_t time, bool continued) {
	if (!continued) {
		timer_tick = 0;
	}
	while (time) {
		if (timer_tick != 0) {
			time--;
			timer_tick--;
		}
	}
}
